<template>
  <el-drawer
    v-model="visible"
    title="执行历史"
    size="60%"
    :destroy-on-close="true"
  >
    <div class="history-drawer">
      <el-table
        v-loading="loading"
        :data="historyList"
        style="width: 100%"
      >
        <el-table-column prop="startTime" label="执行时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="progress" label="进度" width="180">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :status="getProgressStatus(row.status)"
            />
          </template>
        </el-table-column>

        <el-table-column label="参数">
          <template #default="{ row }">
            <el-button link type="primary" @click="showParams(row)">
              查看参数
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="结果">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'completed'"
              link
              type="primary"
              @click="showResult(row)"
            >
              查看结果
            </el-button>
            <el-button
              v-else-if="row.status === 'failed'"
              link
              type="danger"
              @click="showError(row)"
            >
              查看错误
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              :disabled="!canRerun(row)"
              @click="rerunExecution(row)"
            >
              重新执行
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && historyList.length === 0" class="empty-tip">
        暂无执行记录
      </div>

      <!-- 参数对话框 -->
      <el-dialog
        v-model="paramsDialog.visible"
        title="执行参数"
        width="600px"
      >
        <json-viewer
          :value="paramsDialog.data"
          :expand-depth="3"
          copyable
          boxed
          sort
        />
      </el-dialog>

      <!-- 结果对话框 -->
      <el-dialog
        v-model="resultDialog.visible"
        title="执行结果"
        width="800px"
      >
        <div v-if="resultDialog.data" class="result-content">
          <img
            v-if="resultDialog.data.type === 'image'"
            :src="resultDialog.data.data"
            class="result-image"
            alt="生成结果"
          />
          <pre v-else-if="resultDialog.data.type === 'json'" class="result-json">
            {{ JSON.stringify(resultDialog.data.data, null, 2) }}
          </pre>
          <div v-else class="result-text">
            {{ resultDialog.data.data }}
          </div>
        </div>
      </el-dialog>

      <!-- 错误对话框 -->
      <el-dialog
        v-model="errorDialog.visible"
        title="错误信息"
        width="600px"
      >
        <pre class="error-message">{{ errorDialog.message }}</pre>
      </el-dialog>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import JsonViewer from 'vue-json-viewer'
import dayjs from 'dayjs'

const props = defineProps<{
  modelValue: boolean
  workflowId: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const workflowStore = useWorkflowStore()
const loading = ref(false)
const historyList = ref<any[]>([])

// 对话框状态
const paramsDialog = ref({
  visible: false,
  data: null as any
})

const resultDialog = ref({
  visible: false,
  data: null as any
})

const errorDialog = ref({
  visible: false,
  message: ''
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 加载历史记录
const loadHistory = async () => {
  try {
    loading.value = true
    historyList.value = await workflowStore.getWorkflowHistory(props.workflowId)
  } catch (error: any) {
    ElMessage.error(error.message || '加载历史记录失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'danger'
    case 'running':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'running':
      return '执行中'
    default:
      return '等待中'
  }
}

// 获取进度条状态
const getProgressStatus = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'exception'
    case 'running':
      return ''
    default:
      return ''
  }
}

// 是否可以重新执行
const canRerun = (row: any) => {
  return row.status === 'failed' || row.status === 'completed'
}

// 查看参数
const showParams = (row: any) => {
  paramsDialog.value = {
    visible: true,
    data: row.params
  }
}

// 查看结果
const showResult = (row: any) => {
  resultDialog.value = {
    visible: true,
    data: row.result
  }
}

// 查看错误
const showError = (row: any) => {
  errorDialog.value = {
    visible: true,
    message: row.error
  }
}

// 重新执行
const rerunExecution = async (row: any) => {
  try {
    await workflowStore.executeWorkflow(props.workflowId, row.params)
    ElMessage.success('已重新执行')
    loadHistory()
  } catch (error: any) {
    ElMessage.error(error.message || '重新执行失败')
  }
}

// 监听抽屉显示状态
watch(() => visible.value, (newValue) => {
  if (newValue && props.workflowId) {
    loadHistory()
  }
})
</script>

<style scoped lang="scss">
.history-drawer {
  padding: 16px;

  .empty-tip {
    text-align: center;
    color: #999;
    padding: 32px 0;
  }

  .result-content {
    .result-image {
      max-width: 100%;
      border-radius: 4px;
    }

    .result-json,
    .result-text {
      margin: 0;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 4px;
      overflow: auto;
    }
  }

  .error-message {
    margin: 0;
    padding: 16px;
    background: #fff2f0;
    border-radius: 4px;
    color: #f56c6c;
    white-space: pre-wrap;
  }

  :deep(.json-viewer) {
    background: #f8f9fa;
    border-radius: 4px;
  }
}
</style> 